//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	ManagedDisposableInfo.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;

namespace Smart.Common
{
	/// <summary>
	/// Disposable info
	/// </summary>
	[DebuggerStepThrough]
	public class ManagedDisposableInfo
	{
		public string[] Keys;

		public bool ShouldBeDisposed;
		public IDisposable Disposable;
		public object[] Args;

		public int UseCount;
		public int RefCount;

		public void IncrementUsage()
		{
			Interlocked.Increment(ref UseCount);
		}

		public void IncrementRef()
		{
			Interlocked.Increment(ref RefCount);
		}

		public long DecrementRef()
		{
			return Interlocked.Decrement(ref RefCount);
		}

		[MethodImpl(MethodImplOptions.Synchronized)]
		public void Release()
		{
			if (!ShouldBeDisposed)
				return;

			if (RefCount > 0)
			{
				H.LT("ManagedDisposable.Exception: disposable was leaked ({0} times)!", RefCount);
			}

			if (Disposable == null)
				return;

			Disposable.Dispose();
			Disposable = null;
		}
	}
}